<?php

namespace App\Http\Middleware;

use App\Services\Handle\Handle;
use Closure;

class RequestFilter
{
    /**请求过滤中间件
     * @param $request
     * @param Closure $next
     * @param null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        //获取请求对象参数keys
        $keyWorld = '';
        //获取当前操作
        $Handle = new Handle();
        $currentAction = $Handle->getCurrentAction();
        //过滤路径
        $symbol = config('RequestFilter');
        //过滤开关
        $filter = true;
        foreach ($request->request->keys() as $key => $param){
            //过滤参数值中的xss对象
            //xss过滤关键字读取配置
            if ($param != '_token'){
                foreach ($symbol['Path'] as $controller => $item){

                    foreach ($item as $action => $input){
                        if ($currentAction['controller'] == $controller && $currentAction['method'] == $action && in_array($param,$input)){
                            $filter = false;
                        }
                    }

                }
                if ($filter){
                    $value = $request->request->get($param);
                    //防止多维数组提交
                    $value = is_array($value) ? implode('|',MultipleToOne($value)) : $value;
                    //过滤
                    $filtered = self::filterCallBack($value,$symbol);
                    $keyWorld .= $filtered;
                }
            }
        }
        //提示
        if (!empty($keyWorld)){
            \Log::info(\Auth::user()->name."的输入中含有:".$keyWorld.'关键字');
            if ($request->ajax()){
                //ajax
                return response()->json(['code'=>500,'msg'=>'您的输入中含有恶意或非法字符,请重新输入']);
            }else{

                abort(500,'您的输入中含有恶意或非法字符,请重新输入');
            }
        }
        return $next($request);
    }

    /**
     * 过滤参数
     * @param string $param
     * @param array $symbol
     * @return string $resStr
     */
    public static function filterCallBack ($param,$symbol) {
        $resStr = '';
        if (is_string($param)) {
            //批量处理
            $temp = array_merge($symbol['sqlPmz'], $symbol['sqlSgm'], $symbol['specSymbol']);
            foreach ($temp as $k => $v) {
                //关键字查找
                if (strpos($param, $v) !== false) {
                    //例外
                    if (!in_array($v,$symbol['exception'])){

                        foreach ($symbol['exception'] as $exs){


                            if (strpos($param,$exs) === false){
                                $resStr .= $v .',';
                            }
                        }
                    }
                }

            }
        }
        return rtrim($resStr,',');
    }

}
